using Sitecore.Data.Items;
using Sitecore.Resources.Media;

namespace ColorBox4Sitecore.Colorbox
{
    public static class ColorboxHelper
    {
        /// <summary>
        /// Get the minimal value for the sclaing of the pictures
        /// </summary>
        /// <param name="max"></param>
        /// <param name="size"></param>
        /// <param name="inner"></param>
        /// <returns></returns>
        public static int? GetSize(int? max, int? size, int? inner)
        {
            int? min = null;
            if (max.HasValue)
            {
                if (size.HasValue)
                {
                    if (max < size)
                        min = max;
                    else
                        min = size;

                    if (inner.HasValue)
                    {
                        if (inner < min)
                            min = inner;
                    }
                }
                else
                {
                    if (inner.HasValue)
                    {
                        if (max < inner)
                            min = max;
                        else
                            min = inner;
                    }
                }
            }
            else
            {
                if (size.HasValue)
                {
                    if (inner.HasValue)
                    {
                        if (size < inner)
                            min = size;
                        else
                            min = inner;
                    }
                    else
                        min = size;
                }
                else
                    min = inner;
            }

            return min;
        }

        /// <summary>
        /// Return the picture url with the correct extention (not .ashx)
        /// </summary>
        /// <returns></returns>
        public static string GetPictureUrl(MediaItem media, bool scalePhotos, int? scaleHeight, int? scaleWidth)
        {
            string url = MediaManager.GetMediaUrl(media).Replace(".ashx", "." + media.Extension);

            if (scalePhotos) //Fix for the bug with the scale images
                url = string.Format("{0}?mh={1}&mw={2}", url, scaleHeight, scaleWidth);

            return url;
        }
    }
}